/**
 * Copyright 2018 人人开源 http://www.renren.io
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.rzt.cft.admin.controller.sys;


import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.rzt.cft.constant.ServiceStatus;
import com.rzt.cft.dto.ResponseData;
import com.rzt.cft.dto.sys.SysUserDto;
import com.rzt.cft.param.sys.LoginParam;
import com.rzt.cft.utils.JwtUtil;
import com.rzt.cft.utils.ShiroUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 登录相关方法
 *
 * @author zhongzhong
 * @since 2019-12-31
 */
@Controller
@RequestMapping("/v1/sys-login/")
@Api(tags = "后台登录接口")
public class SysLoginController {

	@Autowired
	private Producer producer;

	@ApiOperation("登录 -> 获取验证码")
	@GetMapping("captcha")
	public void captcha(HttpServletResponse response)throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        //保存到shiro session
        ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);
        
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
	}
	
	/**
	 * 登录
	 */
	@ApiOperation("登录")
	@ResponseBody
	@PostMapping(value = "login")
	public ResponseData login(@RequestBody LoginParam loginParam) {
		String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
		if(!loginParam.getCaptcha().equalsIgnoreCase(kaptcha)){
			return ResponseData.error(ServiceStatus.CODE_ERROR);
		}
		try{
			Subject subject = ShiroUtils.getSubject();
			UsernamePasswordToken token = new UsernamePasswordToken(loginParam.getUserName(), loginParam.getPassWord());
			subject.login(token);
			SysUserDto user = ShiroUtils.getSysUser();
			return ResponseData.ok(JwtUtil.createToken(user));
		}catch (UnknownAccountException e) {
			return ResponseData.error(e.getMessage());
		}catch (IncorrectCredentialsException e) {
			return ResponseData.error(ServiceStatus.USER_NAMEPWDERROR);
		}catch (LockedAccountException e) {
			return ResponseData.error("账号已被锁定,请联系管理员");
		}catch (AuthenticationException e) {
			return ResponseData.error("账户验证失败");
		}
	}
	
	/**
	 * 退出
	 */
	@ApiOperation("登录 -> 退出")
	@PostMapping(value = "logout")
	@ResponseBody
	public ResponseData logout() {
		ShiroUtils.logout();
		return ResponseData.ok();
	}
	
}
